package com.lsf.dunlian;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSONObject;
import com.lsf.dunlian.config.NettyConfig;
import com.lsf.dunlian.config.PreferenceUtil;
import com.lsf.dunlian.constant.Constant;
import com.lsf.dunlian.entity.FileEntity;
import com.lsf.dunlian.entity.MessageEntity;
import com.lsf.dunlian.netty.SimpleClientHandler;

import java.util.ArrayList;
import java.util.List;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

public class Myappliction extends Application {
    public static Channel channel;
    public static Activity mContext;
    public static Activity mainActivity;
    public static List<FileEntity> fileEntityList = new ArrayList<>();
    @Override
    public void onCreate() {
        super.onCreate();
        initLifecycle();
    }


    private void initLifecycle() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

                if (activity.getParent() != null) {//如果这个视图是嵌入的子视图
                    mContext = activity.getParent();
                } else {
                    mContext = activity;
                }
                Log.e("zgmzgmzgm", mContext.getPackageName());
            }

            @Override
            public void onActivityStarted(Activity activity) {
                if (activity.getParent() != null) {
                    mContext = activity.getParent();
                } else {
                    mContext = activity;
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {
                if (activity.getParent() != null) {
                    mContext = activity.getParent();
                } else {
                    mContext = activity;
                }
            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {

            }
            //.....
        });
    }

    public static void netty() {
//        if (StringUtils.isEmpty(PreferenceUtil.getSharedPreference(Constants.Login.PARAM_USERID)))return;

        if (Myappliction.channel != null && Myappliction.channel.isActive()) return;
        new Thread(() -> {
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                Bootstrap b = new Bootstrap();
                SimpleClientHandler mClientHandler = new SimpleClientHandler(mainActivity);
                b.group(workerGroup).channel(NioSocketChannel.class)
                        .option(ChannelOption.SO_KEEPALIVE, true)
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel channel) {
                                channel.pipeline().addLast(new IdleStateHandler(0, 60, 0));
                                channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,
                                        Unpooled.copiedBuffer(NettyConfig.DATA_PACK_SEPARATOR.getBytes())));
                                channel.pipeline().addLast("encoder", new StringEncoder());
                                channel.pipeline().addLast("decoder", new StringDecoder());
                                channel.pipeline().addLast(mClientHandler);
                            }
                        });
                ChannelFuture channelFuture = b.connect("139.155.176.187", 9999).sync();
                if (channelFuture.isSuccess()) {
                    //发送数据给服务器
                    MessageEntity user = new MessageEntity();
                    user.msgType = "login";
                    user.createUserId = PreferenceUtil.getSharedPreference(Constant.USERID);
                    Myappliction.channel = channelFuture.channel();
                    Myappliction.channel.writeAndFlush(JSONObject.toJSONString(user) + NettyConfig.DATA_PACK_SEPARATOR);
                }
                channelFuture.channel().closeFuture().sync();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                workerGroup.shutdownGracefully();
            }
        }).start();
    }
}
